import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Character, Conversation, Message } from '@/types/roleplay';
import { characterApi, conversationApi } from '@/services/api';

export const useRoleplayStore = defineStore('roleplay', () => {
  // 状态
  const characters = ref<Character[]>([]);
  const currentCharacter = ref<Character | null>(null);
  const conversations = ref<Conversation[]>([]);
  const currentConversation = ref<Conversation | null>(null);
  const messages = ref<Message[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const activeCharacters = computed(() =>
    characters.value.filter((char) => char.isActive)
  );

  const currentCharacterConversations = computed(() =>
    currentCharacter.value
      ? conversations.value.filter(
          (conv) => conv.characterId === currentCharacter.value!.id
        )
      : []
  );

  // 角色相关方法
  const generateCharacter = async (background: string) => {
    try {
      loading.value = true;
      error.value = null;

      const response = await characterApi.generate({ background });
      if (response.success && response.data) {
        characters.value.unshift(response.data);
        return response.data;
      }
      throw new Error(response.error || '生成角色失败');
    } catch (err: any) {
      error.value = err.message || '生成角色失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const loadCharacters = async () => {
    try {
      loading.value = true;
      error.value = null;

      console.log('Store: 开始调用API获取角色列表...');
      const response = await characterApi.getAll();
      console.log('Store: API响应:', response);

      if (response.success && response.data) {
        characters.value = response.data;
        console.log('Store: 角色列表已更新:', characters.value);
      } else {
        console.error('Store: API响应失败:', response);
      }
    } catch (err: any) {
      console.error('Store: 加载角色失败:', err);
      error.value = err.message || '加载角色失败';
    } finally {
      loading.value = false;
    }
  };

  const selectCharacter = async (character: Character) => {
    currentCharacter.value = character;
    await loadConversations(character.id);
  };

  const deleteCharacter = async (id: string) => {
    try {
      loading.value = true;
      error.value = null;

      const response = await characterApi.delete(id);
      if (response.success) {
        characters.value = characters.value.filter((char) => char.id !== id);
        if (currentCharacter.value?.id === id) {
          currentCharacter.value = null;
          conversations.value = [];
          currentConversation.value = null;
          messages.value = [];
        }
      }
    } catch (err: any) {
      error.value = err.message || '删除角色失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 对话相关方法
  const loadConversations = async (characterId: string) => {
    try {
      const response = await conversationApi.getByCharacterId(characterId);
      if (response.success && response.data) {
        conversations.value = response.data;
      }
    } catch (err: any) {
      error.value = err.message || '加载对话失败';
    }
  };

  const createConversation = async (characterId: string, title?: string) => {
    try {
      loading.value = true;
      error.value = null;

      const response = await conversationApi.create({ characterId, title });
      if (response.success && response.data) {
        conversations.value.unshift(response.data);
        return response.data;
      }
      throw new Error(response.error || '创建对话失败');
    } catch (err: any) {
      error.value = err.message || '创建对话失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const selectConversation = async (conversation: Conversation) => {
    try {
      loading.value = true;
      error.value = null;

      currentConversation.value = conversation;
      const response = await conversationApi.getById(conversation.id);
      if (response.success && response.data) {
        messages.value = response.data.messages;
      }
    } catch (err: any) {
      error.value = err.message || '加载对话失败';
    } finally {
      loading.value = false;
    }
  };

  const sendMessage = async (content: string) => {
    if (!currentConversation.value) {
      throw new Error('请先选择对话');
    }

    try {
      loading.value = true;
      error.value = null;

      const response = await conversationApi.sendMessage(
        currentConversation.value.id,
        { content }
      );

      if (response.success && response.data) {
        messages.value.push(response.data.userMessage);
        messages.value.push(response.data.assistantMessage);
        return response.data;
      }
      throw new Error(response.error || '发送消息失败');
    } catch (err: any) {
      error.value = err.message || '发送消息失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const deleteConversation = async (id: string) => {
    try {
      loading.value = true;
      error.value = null;

      const response = await conversationApi.delete(id);
      if (response.success) {
        conversations.value = conversations.value.filter(
          (conv) => conv.id !== id
        );
        if (currentConversation.value?.id === id) {
          currentConversation.value = null;
          messages.value = [];
        }
      }
    } catch (err: any) {
      error.value = err.message || '删除对话失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 清除错误
  const clearError = () => {
    error.value = null;
  };

  return {
    // 状态
    characters,
    currentCharacter,
    conversations,
    currentConversation,
    messages,
    loading,
    error,

    // 计算属性
    activeCharacters,
    currentCharacterConversations,

    // 方法
    generateCharacter,
    loadCharacters,
    selectCharacter,
    deleteCharacter,
    loadConversations,
    createConversation,
    selectConversation,
    sendMessage,
    deleteConversation,
    clearError,
  };
});
